﻿#define DEBUG_AGENT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using QuickTasks.ViewModels.Data;
using QuickTasks.GeocodeService;
using System.Windows.Navigation;
using QuickTasks.ViewModels.Properties;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using LocalSettings;
using Microsoft.Phone.Net.NetworkInformation;
using System.IO;
using QuickTasks.Views.BackGrounds;
using Microsoft.Advertising.Mobile.UI;


namespace QuickTasks.Views.Places
{
    public partial class Address : PhoneApplicationPage
    {


        #region Global
        string hisId = "";
        public static bool Auto = false;
        string Id;


        #endregion

        #region constructor

        public Address()
        {
            InitializeComponent();
          
            Loaded += new RoutedEventHandler(Address_Loaded);


        }





       
        void Address_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.NavigationContext.QueryString.ContainsKey("Id"))
                {
                    ApplicationTitle.Text = "QUICK TASKS - EDIT LOCATION";
                    Id = NavigationContext.QueryString["Id"];
                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        var Add = from i in context.Add where i.id.ToString() == Id select i;
                        foreach (var info in Add)
                        {
                            TbxName.Text = info.name;
                            TbxAddress.Text = info.address;
                            TbxCity.Text = info.city;
                            TbxState.Text = info.state;
                            TbxCountry.Text = info.country;
                            TbxZipcode.Text = info.zipcode;
                        }
                    }
                }
                else
                {
                    ApplicationTitle.Text = "QUICK TASKS - ADD LOCATION";
                }
                if (this.NavigationContext.QueryString.ContainsKey("Gps"))
                {

                    ApplicationTitle.Text = "QUICK TASKS - ADD LOCATION";
                  
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  Address_Loaded event In Address.xaml page", ex);
            }

        }
        #endregion

        #region Latitude and langtitu  events

        private void ApplicationBarSaveAddListButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (TbxName.Text == "")
                {
                    tblkMobileValidation.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    tblkMobileValidation.Visibility = Visibility.Collapsed;
                }
                string address = string.Empty;
                if (TbxAddress.Text == "")
                {
                    tblkMobileValidation1.Visibility = Visibility.Visible;
                    return;
                }
                else
                {
                    
                    tblkMobileValidation1.Visibility = Visibility.Collapsed;
                    while (TbxAddress.Text.Length > 28)
                    {
                        TbxAddress.Text = TbxAddress.Text.Substring(0, TbxAddress.Text.LastIndexOf(' '));
                    }
                }
               
             

                if (NetworkInterface.GetIsNetworkAvailable() && NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
                {
                    if (Auto == true)
                    {
                        Auto = false;
                        AddAddress objAddress = new AddAddress();
                        hisId = objAddress.SaveAddress(TbxName.Text, TbxAddress.Text, TbxCity.Text, TbxState.Text, TbxCountry.Text, TbxZipcode.Text, Id);
                        SaveLocation();
                        NavigationService.GoBack();
                    }
                    else
                    {
                        GetLattAndLong(TbxCity.Text);
                    }
                    
                   
                }
                else
                {

                    App.Latitude = 0;
                    App.Longitude = 0;
                    AddAddress objAddress = new AddAddress();
                    hisId = objAddress.SaveAddress(TbxName.Text, TbxAddress.Text, TbxCity.Text, TbxState.Text, TbxCountry.Text, TbxZipcode.Text, Id);
                    SaveLocation();
                    NavigationService.GoBack();


                }

            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  ApplicationBarSaveAddListButton_Click event In Address.xaml page", ex);
            }
        }

        private void GetLattAndLong(string address)
        {
            GeocodeRequest geocodeRequest = new GeocodeRequest();
            RequestBase req = new RequestBase();
            geocodeRequest.Credentials = new Credentials();
            geocodeRequest.Credentials.ApplicationId = "AmivBwP5dxW9Uih0JzRpHA_Sln8fHpHw7WB5TOkK9RCXOECJWZAXYU1U8UQ47fUr";
            geocodeRequest.Query = address;
            ConfidenceFilter[] filters = new ConfidenceFilter[1];
            filters[0] = new ConfidenceFilter();
            filters[0].MinimumConfidence = GeocodeService.Confidence.High;
            GeocodeOptions geocodeOptions = new GeocodeOptions();
            geocodeRequest.Options = geocodeOptions;
            GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
            geocodeService.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(geocodeService_GeocodeCompleted);
            geocodeService.GeocodeAsync(geocodeRequest);
        }
        void geocodeService_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
        {
            GeocodeResponse geocodeResponse = e.Result;
            try
            {
                App.Latitude = geocodeResponse.Results[0].Locations[0].Latitude;
                App.Longitude = geocodeResponse.Results[0].Locations[0].Longitude;
            }
                
            catch (Exception ex)
            {
                tblkcityValidation.Visibility = Visibility.Visible;
                return;
            }
            AddAddress objAddress = new AddAddress();
            hisId = objAddress.SaveAddress(TbxName.Text, TbxAddress.Text, TbxCity.Text, TbxState.Text, TbxCountry.Text, TbxZipcode.Text, Id);
            SaveLocation();
            NavigationService.GoBack();

        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            while (NavigationService.BackStack.ToList().Any(x => x.Source.ToString().Contains("Address.xaml")))
            {
                NavigationService.RemoveBackEntry();
            }
        }


        public void SaveLocation()
        {
            try
            {
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {
                    IQueryable<QuickTasks.ViewModels.Tables.Address> addressele = from i in context.Add where i.id.ToString() == hisId select i;
                    QuickTasks.ViewModels.Tables.Address add = addressele.FirstOrDefault();
                    {
                        add.latitude = App.Latitude.ToString();
                        add.longitude = App.Longitude.ToString();
                    };
                    context.SubmitChanges();

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  SaveLocation method In Address.xaml page", ex);
                return;
            }
        }


        #endregion

        private void TbxAddress_GotFocus(object sender, RoutedEventArgs e)
        {
            tblkAddressValidation.Visibility = Visibility.Collapsed;
        }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
               
                string status = IsolatedSettings.getSettingsStringValue("Locationserviceon");
                if (status == "true")
                {

                    if (IsolatedSettings.getSettingsStringValue("GeoLocationStatus") == "true")
                    {
                        if (!string.IsNullOrEmpty(App.Name))
                        {
                            TbxName.Text = App.Name;
                            App.Name = string.Empty;
                        }

                        if (!string.IsNullOrEmpty(App.Address))
                        {
                            TbxAddress.Text = App.Address;
                            App.Address = string.Empty;
                        }
                        if (!string.IsNullOrEmpty(App.Location))
                        {
                            Auto = true;
                            TbxCity.Text = App.Location;
                            App.Location = string.Empty;
                        }
                        if (!string.IsNullOrEmpty(App.State))
                        {
                            TbxState.Text = App.State;
                            App.State = string.Empty;
                        }
                        if (!string.IsNullOrEmpty(App.ZipCode))
                        {
                            TbxZipcode.Text = App.ZipCode;
                            App.ZipCode = string.Empty;
                        }
                        if (!string.IsNullOrEmpty(App.Country))
                        {
                            TbxCountry.Text = App.Country;
                            App.Country = string.Empty;
                        }
                       
                    }

                }
                else
                {
                    MessageBoxResult resultLocation = MessageBox.Show("To use this feature,enable Location Services in phone settings", "Add Location", MessageBoxButton.OK);

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  ApplicationBarMenuItem_Click event In Address.xaml page", ex);

            }
        }

        private void TbxName_TextChanged(object sender, TextChangedEventArgs e)
        {
            App.Name = TbxName.Text;
        }



    }
}